package com.tender;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tender.pojo.User;
import com.tender.utils.ESOperationTemplate;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.xcontent.XContentType;

public class A_4_InsertDoc {

    public static void main(String[] args) throws Exception {
        ESOperationTemplate.process(client -> {
            try {
                // 新增文档 - 请求对象
                IndexRequest indexRequest = new IndexRequest();
                // 设置索引及唯一性标识
                indexRequest.index("user2").id("1001");

                User user = new User();
                user.setAge(30);
                user.setSex("male");
                user.setUsername("竹山居士");

                ObjectMapper objectMapper = new ObjectMapper();

                String productJson = objectMapper.writeValueAsString(user);
                // 添加文档数据，数据格式为 JSON 格式
                indexRequest.source(productJson, XContentType.JSON);
                IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);

                // 打印结果信息
                System.out.println("_index:" + response.getIndex());
                System.out.println("_id:" + response.getId());
                System.out.println("_result:" + response.getResult());
            } catch (Exception e) {
                // do nothing!
            }

            return null;
        });
    }
}
